package com.gwz.cardserver.global;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Data
@Component
public class GlobalCache {
    private ConcurrentHashMap<String, ChannelHandlerContext> accountStringMap = new ConcurrentHashMap();
    private ConcurrentHashMap<ChannelHandlerContext, String> accountChannelContextMap = new ConcurrentHashMap();

    public void addAccount(String accountId, ChannelHandlerContext channelHandlerContext) {
        accountStringMap.put(accountId, channelHandlerContext);
        accountChannelContextMap.put(channelHandlerContext, accountId);
    }

    public void removeAccount(ChannelHandlerContext channelHandlerContext) {
        String accountId = accountChannelContextMap.get(channelHandlerContext);
        if (StrUtil.isNotEmpty(accountId)) {
            accountStringMap.remove(accountId);
        }
        accountChannelContextMap.remove(channelHandlerContext);
    }

    public void removeAccount(String accountId) {
        ChannelHandlerContext channelHandlerContext = accountStringMap.get(accountId);
        accountStringMap.remove(accountId);
        accountChannelContextMap.remove(channelHandlerContext);
    }


    public  String getUserIdBYChannel(ChannelHandlerContext channelHandlerContext){
        return  accountChannelContextMap.get(channelHandlerContext);
    }

    public  ChannelHandlerContext getChannelByUserId(String userId){
        return  accountStringMap.get(userId);
    }
}
